package com.auth2server.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName JwtAuthorizationServerConfig
 * @Description TODO
 * @Author zl-pc
 * @Date 2020/8/25
 * @Version 1.0
 **/
@ConditionalOnProperty(prefix="jdbc",name = "flag", havingValue = "jwt")
@Configuration
//开启oauth2,auth server模式
@EnableAuthorizationServer
public class JwtAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    /** 客户端详情服务 */
    @Autowired
    private ClientDetailsService clientDetailsService;
    /** 令牌持久化配置 */
    @Autowired
    private TokenStore tokenStore;
    //密码模式才需要配置,认证管理器
    @Autowired
    private AuthenticationManager authenticationManager;
    //用户信息
    @Autowired
    private UserDetailsService userDetailsService;
    //注入数据源信息
    @Autowired
    private DataSource dataSource;
    //捕获异常信息
    @Autowired
    private WebResponseExceptionTranslator webResponseExceptionTranslator;
    /** jwtToken解析器 */
    @Autowired
    private JwtAccessTokenConverter tokenConverter;
    //token 扩展信息
    @Autowired
    private TokenEnhancer tokenEnhancer;

    //配置token管理服务
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        // 支持使用refresh token刷新access token
        defaultTokenServices.setSupportRefreshToken(true);
        // 允许重复使用refresh token
        defaultTokenServices.setReuseRefreshToken(true);
        //配置token的存储方法
        defaultTokenServices.setTokenStore(tokenStore);
        //配置token增强,把一般token转换为jwt token
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> list = new ArrayList<>();
        list.add(tokenEnhancer); //增加扩展信息，例如token中增加用户信息，以及其他信息
        list.add(tokenConverter); //通过jwt生成token信息
//        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenConverter));
        tokenEnhancerChain.setTokenEnhancers(list);
        defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);
        return defaultTokenServices;
    }

    //把上面的各个组件组合在一起
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenGranter(tokenGranter(endpoints)) //增加验证码登陆信息
                .userDetailsService(userDetailsService)//若无，refresh_token会有UserDetailsService is required错误
                .tokenServices(tokenServices())
                .exceptionTranslator(webResponseExceptionTranslator);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
        List<TokenGranter> granters = new ArrayList<TokenGranter>(Arrays.asList(endpoints.getTokenGranter()));
        granters.add(new SMSCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(),userDetailsService));
        return new CompositeTokenGranter(granters);
    }


}
